<template>
  <div id="editadmin" style="padding: 20px;width: 80%">
    <div style="margin-bottom: 30px;color: #c5b3e5;font-weight: bold">编辑用户</div>
    <el-form :inline="true" :model="form" :rules="rules" ref="ruleForm" label-width="100px">
      <el-form-item label="卡号：">
        <el-input v-model="form.admincode" disabled></el-input>
      </el-form-item>
      <el-form-item label="名字：" prop="name">
        <el-input v-model="form.name" placeholder="请输入名字..."></el-input>
      </el-form-item>
      <el-form-item label="电话号码：" prop="phone">
        <el-input v-model.number="form.phone" placeholder="请输入电话号码..."></el-input>
      </el-form-item>
      <el-form-item label="邮箱：" prop="email">
        <el-input v-model="form.email" placeholder="请输入邮箱..."></el-input>
      </el-form-item>
    </el-form>

    <div style="text-align: center;margin-top: 30px">
      <el-button type="primary" @click="update">提交</el-button>
      <el-button type="info" @click="cancel" plain>取消</el-button>
    </div>
  </div>
</template>

<script>
import request from "@/utils/request";

export default {
  name: "EditAdmin",

  data() {
    const checkName = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('君の名前は？'));
      }
      callback();
    };
    const checkPhone = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('手机号不能为空'));
      }
      if (!/^1[3-9]\d{9}$/.test(value)) {
        callback(new Error('请输入正确的11位手机号码'));
      }
      callback();
    };
    const checkEmail = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('邮箱不能为空'));
      }
      if (!/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(value)) {
        callback(new Error('请输入正确的邮箱格式'));
      }
      callback();
    };
    return {
      form: {},
      rules: {
        name: [
          {validator: checkName, trigger: 'blur'},
          {min: 2, max: 8, message: '长度在 2 到 8 个字符', trigger: 'blur'}
        ],
        phone: [
          {validator: checkPhone, trigger: 'blur'},
        ],
        email: [
          {validator: checkEmail, trigger: 'blur'},
        ],
      }
    }
  },
  created() {
    const id = this.$route.query.id
    request.get('/admin/' + id).then(res => {

      if (res.data){
        this.form = res.data
      }
    })
  },
  methods: {
    update() {
      this.$refs["ruleForm"].validate((valid) => {
        if (valid) {
          request.put("/admin/update", this.form).then(res => {
            if (res.code === '200') {
              this.$notify.success("编辑成功")
              this.$router.push("/admin")
            } else {
              this.$notify.error(res.msg)
            }

          })
        } else {
          this.$notify.error("再给你一次机会");
          return false;
        }
      })
    },
    cancel() {
      this.$notify.success("キャンセル完了")
      this.$router.push("/admin")
    }
  }
}
</script>

<style scoped>

</style>